#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json

import pika as pika


class Producer:
    response = None

    # 定义接收到返回消息的处理方法
    def __init__(self):
        credentials = pika.PlainCredentials('guest', 'guest')  # mq用户名和密码
        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters(host = 'localhost', port = 5672, virtual_host = '/', credentials = credentials))

    def on_response(self, ch, method, props, body):
        print("这里执行了吗？")
        self.response = body
        print(body.decode())

    def run(self):
        # print('rabbitMq test')

        channel = self.connection.channel()
        result = channel.queue_declare(queue = 'rabbit-test')
        callback_queue = result.method.queue
        print(callback_queue)
        channel.basic_consume(on_message_callback = self.on_response,
                              auto_ack = True,
                              queue = callback_queue)
        message = json.dumps({'OrderId': "1000%s" % 10})
        # 向队列插入数值 routing_key是队列名
        channel.basic_publish(exchange = '', routing_key = 'rabbit-test', body = message,
                              properties = pika.BasicProperties(reply_to = 'amq.rabbitmq.reply-to'), )
        self.connection.process_data_events()
        # print(message)
        while self.response is not None:
            print('执行成功了')
            print(self.response)


if __name__ == '__main__':
    producer = Producer()
    producer.run()
